from socket import *
from matplotlib import pyplot as plt
import sys, os, struct
import math
from threading import Thread, Lock

sys.path.append(os.path.join(sys.path[0], '../..'))

from csi_data import CSI_Data
from csi_config import read_setting

PORT = int(read_setting('port'))

BUF_SIZE = 2048
client = socket(AF_INET, SOCK_STREAM, 0)
client.connect(('127.0.0.1', PORT))
totalcnt = 0


def getmodl(arr):
    return [math.sqrt(item.real ** 2 + item.imag ** 2) for item in arr]


def getmod(item):
    return math.sqrt(item.real ** 2 + item.imag ** 2)


def read_t():
    alive = True
    while alive:
        try:
            buf = client.recv(BUF_SIZE)
            if buf is None:
                client.close()
                sys.exit(-2)
            i = struct.unpack('>H', buf[:2])
            if i[0] == len(buf) - 2:  # correct package check - 1
                global totalcnt
                totalcnt += 1

                if buf[2] == 187:  # correct package check - 2
                    dat = CSI_Data(buf[3:])
                    csi_update(dat)
        except struct.error as e:
            alive=False
            print(e)
            client.close()




def csi_update(dat):
    # if dat is not None:
    #     Nrx = dat.Nrx
    #     Ntx = dat.Ntx
    #     for i in range(Ntx):
    #         for j in range(Nrx):
    #             csi_t = dat.csi[i][j]
    #             if l[i * 3 + j] is not None:
    #                 l[i * 3 + j][0].set_ydata(getmod(csi_t))
    #                 plt.draw()
    if dat is not None:
        print(dat.correct)
        csi_t = dat.csi[0][0]
        l[0][0].set_ydata(getmodl(csi_t))
        csi_t = dat.csi[0][1]
        l[1][0].set_ydata(getmodl(csi_t))
        csi_t = [0] * 30
        for i in range(30):
            csi_t[i] = abs(getmod(dat.csi[0][0][i]) - getmod(dat.csi[0][1][i]))
        l[2][0].set_ydata(csi_t)

        plt.draw()


# l = [None for i in range(9)]
# plt.figure('csi_data', figsize=(16, 9))
# for i in range(3):
#     for j in range(3):
#         plt.subplot(330 + i * 3 + j + 1)
#         plt.ylim(0,40)
#         l[i * 3 + j] = plt.plot(range(1, 31), [0 for i in range(30)])

plt.figure()
plt.ylim(0, 80)
l = [None, None, None]
l[0] = plt.plot(range(1, 31), [0 for _ in range(30)], 'ro')
l[1] = plt.plot(range(1, 31), [0 for _ in range(30)], 'bx')
# plt.figure()
# plt.ylim(0,20)
l[2] = plt.plot(range(1, 31), [0 for _ in range(30)], 'g')

read_thread = Thread(target=read_t)

read_thread.start()
plt.show()
read_thread.join()
